package com.lihang.rabbit1.common.exception;


import com.lihang.rabbit1.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理请求参数格式错误的异常 @RequestBody上validate失败后抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String message = fieldErrors.stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.warn("请求参数校验失败(MethodArgumentNotValidException): {}", message);
        log.warn("验证失败的字段: {}", fieldErrors.stream()
                .map(f -> f.getField() + "=" + f.getRejectedValue())
                .collect(Collectors.joining(", ")));
        return Result.fail(400, message);
    }

    /**
     * 处理请求参数格式错误的异常 @RequestParam上validate失败后抛出的异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String message = violations.stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        log.warn("请求参数校验失败(ConstraintViolationException): {}", message);
        log.warn("验证失败详情: {}", violations.stream()
                .map(v -> v.getPropertyPath() + "=" + v.getInvalidValue() + ", 原因: " + v.getMessage())
                .collect(Collectors.joining("; ")));
        return Result.fail(400, message);
    }

    /**
     * 处理请求参数格式错误的异常 @Valid验证参数对象时抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBindException(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String message = fieldErrors.stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.warn("请求参数校验失败(BindException): {}", message);
        log.warn("验证失败的字段: {}", fieldErrors.stream()
                .map(f -> f.getField() + "=" + f.getRejectedValue() + ", 类型: " +
                        (f.getRejectedValue() != null ? f.getRejectedValue().getClass().getName() : "null"))
                .collect(Collectors.joining("; ")));
        return Result.fail(400, message);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.warn("业务异常: {}", e.getMessage());
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return Result.fail(500, "系统异常，请联系管理员");
    }
}